<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    // 通过定义一个类Observer 使用循环递归 使得对象所有属性变为可侦测
    class Observer {
      constructor(value) {
        this.value = value
        if (Array.isArray(value)) {
          // 侦听数组的元素
        } else {
          console.log('传入对象');
          this.walk(value)
        }
      }
      walk(obj) {
        // 获取属性列表
        let keys = Object.keys(obj)
        for(let i in keys) {
          console.log('将所有属性绑定可侦听');
          let key = keys[i]
          defineReactive(obj, key, obj[key])
        }
      }
    }
    function defineReactive(obj, key, value) {
      if (arguments.length === 2) {
        value = obj[key]
      }
      if (typeof value === 'object') {
        new Observer(value)
      }
      console.log(key + '正在绑定');
      Object.defineProperty(obj, key, {
        enumerable: false,
        configurable: false,
        get() {
          console.log('获取值');
          return value
        },
        set(newValue) {
          console.log('修改值');
          if (value === newValue) return
          value = newValue
        }
      })
    }
    let user = {
      name: 'zhangsan',
      age: 12,
      friend: {
        name: 'lisi',
        age: 13
      }
    }
    let userObserver = new Observer(user)
  </script>
</body>
</html>